#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <chrono>

#include <opencv2/opencv.hpp>
#include <grpcpp/grpcpp.h>

#include "image.grpc.pb.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using rcimage::ImageRequest;
using rcimage::CenterReply;
using rcimage::RcRpcServer;
using namespace cv;

class ImageClient {
public:
    ImageClient(std::shared_ptr <Channel> channel)
            : stub_(RcRpcServer::NewStub(channel)) {}

    int Center(cv::Mat image) {
        ImageRequest request;
        std::vector <uchar> data_encode;
        cv::imencode(".jpg", image, data_encode);
        std::string image_str(data_encode.begin(), data_encode.end());
        request.set_image(image_str);

        CenterReply reply;

        ClientContext context;

        Status status = stub_->Center(&context, request, &reply);

        if (status.ok()) {
            return reply.result();
        } else {
            std::cout << status.error_code() << ": " << status.error_message()
                      << std::endl;
            return -1;
        }
    }

private:
    std::unique_ptr <RcRpcServer::Stub> stub_;
};

int main(int argc, char **argv) {
    std::string target_str;
    cv::Mat image = imread("temp.png");
    target_str = "localhost:50051";
    ImageClient greeter(grpc::CreateChannel(
            target_str, grpc::InsecureChannelCredentials()));
    for (int x = 0; x < 100; x += 1) {
        std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
        int reply = greeter.Center(image);
        std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now();
        std::cout << "返回值: " << reply << std::endl;
        auto sec = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
        std::cout << "用时: " << sec.count() << std::endl;
    }
    return 0;
}
